package org.linlinjava.litemall.wx.service;

import com.google.api.client.googleapis.auth.oauth2.GoogleIdToken.Payload;
import org.linlinjava.litemall.core.util.GoogleUtil;
import org.linlinjava.litemall.core.util.IpUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.wx.dto.UserInfoDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static org.linlinjava.litemall.wx.util.WxResponseCode.INVALID_IDTOKEN;
import static org.linlinjava.litemall.wx.util.WxResponseCode.NOT_BIND_EMAIL;

@Service
public class WxGoogleAuthService {

    @Autowired
    private LitemallUserService userService;

    public Object login(String idTokenString, HttpServletRequest request) throws GeneralSecurityException, IOException {
        Payload payload = GoogleUtil.getPayload(idTokenString);
        if(payload != null){
            String email = payload.getEmail();
            List<LitemallUser> users = userService.queryByEmail(email);
            if(users.size() > 0 && users.get(0) != null){
                // 更新登录情况
                LitemallUser user = users.get(0);
                user.setLastLoginTime(LocalDateTime.now());
                user.setLastLoginIp(IpUtil.getIpAddr(request));
                if (userService.updateById(user)) {
                    return ResponseUtil.updatedDataFailed();
                }


                // userInfo
                UserInfoDTO userInfo = new UserInfoDTO();
                userInfo.setNickName(user.getUsername());
                userInfo.setAvatarUrl(user.getAvatar());

                // token
                String token = UserTokenManager.generateToken(user.getId());

                Map<Object, Object> result = new HashMap<Object, Object>();
                result.put("token", token);
                result.put("userInfo", userInfo);
                return ResponseUtil.ok(result);
            }else{
                return ResponseUtil.fail(NOT_BIND_EMAIL,"尚未绑定的邮箱");
            }

        }else{
            return ResponseUtil.fail(INVALID_IDTOKEN,"错误的客户id");
        }
    }
}

